package code_test;

import CSC.ChatServer;
import CSC.MessageBean;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;

public class Server {
    private ServerSocket server;
    public Gson gson = new Gson();
    public  Map<Integer, Message> Messagemap = new HashMap<Integer, Message>();
    public Map<Integer, Socket> SocketMap=new HashMap<Integer, Socket>();
    public  List<Socket> listSocket=new ArrayList<Socket>();
    public void initServer() {
        try {
            server = new ServerSocket(50000);
            createMessage();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 创建消息管理，一直接收消息
     */
    private void createMessage() {
        Socket socket = null;
        try {
            System.out.println("等待用户接入 : ");
            // 使用accept()阻塞等待客户请求
            socket = server.accept();
            listSocket.add(socket);
            System.out.println("用户接入 : " + socket.getPort());
            // 开启一个子线程来等待另外的socket加入
            new Thread(new Runnable() {
                public void run() {
                    createMessage();
                }
            }).start();
            // 向客户端发送信息
            // final OutputStream output = socket.getOutputStream();
            // 从客户端获取信息
            BufferedReader bff = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            // 读取发来服务器信息
            String line = null;
            // 循环一直接收当前socket发来的消息
            // System.out.println("内容 : " + bff.readLine());
            // 获取客户端的信息
            //PrintWriter write=new PrintWriter(socket.getOutputStream());
            line = bff.readLine();
            Message messageBean = gson.fromJson(line, Message.class);
            setUserInforSocket(messageBean,socket);
            if(messageBean.getAudioInputStream()!=null)
                findFriend((int) messageBean.getFriend_ID(),messageBean);
//            if(messageBean.isFirst()){
//                setUserInforSocket(messageBean,socket);
//                //System.out.println("OK");
//            }
//            while (!messageBean.getContent().equals(null)&&!messageBean.getContent().equals("")&&!messageBean.getContent().equals("end")){
//                if(!messageBean.getContent().equals("&")){
//                    System.out.println("用户 : " + messageBean.getUserName());
//                    System.out.println("内容 : " + messageBean.getContent());
//                    findFriend((int) messageBean.getFriendID(),messageBean);
//                }
//                line = bff.readLine();
//                messageBean = gson.fromJson(line, MessageBean.class);
//            }

            // server.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("错误 : " + e.getMessage());

        }
    }
    //将客户端信息存储起来
    private void setUserInforSocket(Message message,Socket socket){
        if(message.getAudioInputStream()!=null)
            Messagemap.put((int) message.getID(), message);
        if(SocketMap.keySet().contains((int) message.getID())==false)
            SocketMap.put((int) message.getID(), socket);
    }
    //通过friendID寻找通信对象，将message对象存储的消息取出，传递出去
    private void findFriend(int id,Message messageBean){
        if(SocketMap.get(id)!=null && SocketMap!=null){
            Socket socket=SocketMap.get(id);
//            Message M=Messagemap.get(id);
//            M.setContent(messageBean.getContent());
            try {
                PrintWriter write0=new PrintWriter(socket.getOutputStream());
//                String t=gson.toJson(M);
                String s=gson.toJson(messageBean);
//                System.out.println(t);
//                System.out.println(s);
                write0.println(s);
                write0.flush();
                Messagemap.remove(messageBean.getID());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
    public static void main(String[] args) {
        new ChatServer().initServer();
    }
}
